package com.cykj.pos.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * 文件工具类
 * author likejian
 */
@Slf4j
public class FileUtils {

    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = new String(Base64Utils.encode(bytes), "UTF-8");
            log.info("将文件[" + path + "]转base64字符串:" + base64);
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        return base64;
    }

    /**
     * @param outFilePathAndName 输出文件路径/xxx.yyy,  base64   base64文件编码字符串
     * @return String
     * @description BASE64解码成File文件
     * @date 2019年11月24日
     * @author rmk
     */
    public static boolean base64ToFile(String outFilePathAndName, String base64) {
        String fileName = FilenameUtils.getName(outFilePathAndName);
        String fullPath = FilenameUtils.getFullPath(outFilePathAndName);
        return base64ToFile(fullPath, base64, fileName);
    }

    /**
     * @param outFilePath 输出文件路径,  base64   base64文件编码字符串,  outFileName  输出文件名
     * @return String
     * @description BASE64解码成File文件
     * @date 2019年11月24日
     * @author rmk
     */
    public static boolean base64ToFile(String outFilePath, String base64, String outFileName) {
        boolean saveSuccess = false;
        File file = null;
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            //创建文件目录
            String filePath = outFilePath;
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
            }
            byte[] bytes = Base64Utils.decode(base64.getBytes());
            file = new File(filePath + "/" + outFileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            saveSuccess = true;
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        return saveSuccess;
    }

    public static int getBase64FileSize(String base64) {
        int strLen = base64.length();
        int fileSize = strLen - (strLen / 8) * 2;
        log.info("文件大小:" + fileSize + "b");
        return fileSize;
    }

    public static String getImageFileSuffix(String base64) {
        if (StringUtils.startsWith(base64, "data:image/png;base64")) {
            return "png";
        } else if (StringUtils.startsWith(base64, "data:image/jpeg;base64")) {
            return "jpeg";
        }
        return "png";
    }

    public static String imageBase64(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在:" + path);
        }
        String base64String;
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            byte[] bytes = outputStream.toByteArray();
            base64String = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return base64String;
    }


    /**
     * 单元测试
     */
    public static void main(String[] args) {
        //定义文件路径
//        String filePath = "/Users/likejian/Downloads/181638861128_.pic.jpg";
//        //将文件转base64字符串
//        String base64 = fileToBase64(filePath);
//        log.info(base64);
//        int strLen = base64.length();
//        int fileSize = strLen - (strLen / 8) * 2;
//        log.info("文件大小:" + fileSize);

//        String s = Base64Util.imgToBase64("/Users/likejian/Downloads/181638861128_.pic.jpg");
//        log.info(s);
//        System.out.printf(base64ToImg(, "/Users/nengwei/Desktop/project/") + "");
//        log.info();
//        //定义输出文件的路径outFilePath和输出文件名outoutFileName
//        String outFilePath = "E:\\FileTest\\logs";
//        String outFileName = "test.log";
//        //将BASE64解码成File文件
//        base64ToFile(outFilePath, base64, outFileName);
    }
}
